package org.jeecg.modules.quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.moenydata.uitils.TimeUtil;
import org.jeecg.modules.demo.pointcount.redis.consumer.SendAndStorageProcess;
import org.jeecg.modules.demo.pointcount.redis.util.Config;
import org.jeecg.modules.demo.pointcount.service.IPonintCountService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @Author zrikka
 * @Date 2021/3/27 15:39
 * 每日清除任务
 *
 */
@Slf4j
public class EverydayClearTaskJob implements Job {

    /** zrikka start */
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        long start = System.currentTimeMillis();// 起始
        clearPointKey(Config.POINT_ADD_EVENT);
        clearTodayUser(Config.POINT_TODAY_USER);
        clearTodayUserNum(Config.POINT_TODAY_USER_NUM);
        long end = System.currentTimeMillis();// 结束
        StringBuffer str = new StringBuffer();
        str.append("清除昨天的打点统计相关数据 凌晨4点执行");
        str.append("总用时: ");
        str.append(end - start);
        str.append("ms");
        log.info(String.format(str.toString()));
    }

    /** zrikka 每天4点执行 */
    /** 清除昨天的打点记录 */
    public void clearPointKey(String key){
        Map<Object, Object> map = redisUtil.hgetAll(key);
        String time = TimeUtil.getBeforeDate(0);
        for (Object mapSet : map.keySet()) {
            String keys = (String) mapSet;// 键  2021-03-19&hc_cq_eventdata&ks&301&0
            String[] keysArr = keys.split("&");
            if(!time.equals(keysArr[0])){
                redisUtil.hdel(key,keys);
            }
        }
    }
    /** 清除昨天的新增用户id集合 */
    public void clearTodayUser(String key){
        Map<Object, Object> map = redisUtil.hgetAll(key);
        String time = TimeUtil.getBeforeDate(0);
        for (Object mapSet : map.keySet()) {
            String timekey = (String) mapSet;// 键  2021-03-19
            String[] arr = timekey.split("&");
            if(!time.equals(arr[0])){
                redisUtil.hdel(key, timekey);
            }
        }
    }
    public void clearTodayUserNum(String key){
        Map<Object, Object> map = redisUtil.hgetAll(key);
        String time = TimeUtil.getBeforeDate(0);
        for (Object mapSet : map.keySet()) {
            String timekey = (String) mapSet;// 键  2021-03-19&userid
            if(!time.equals(timekey)){
                redisUtil.hdel(key, timekey);
            }
        }
    }
    /** zrikka end */
}
